//
//  JLFPhotoCollectionViewController.m
//  TestImageUpload
//
//  Created by he15his on 14/10/18.
//  Copyright (c) 2014年 ven. All rights reserved.
//

#import "SLPhotoCollectionViewController.h"
#import <ImageIO/ImageIO.h>
#import <objc/runtime.h>
#import "SLDeleteAndSelectPhotoViewController.h"
#import "JFBase.h"
#import "JFBasePri.h"

#define kBottomViewHeight 50
#define kSpace 10.0
static char kButtonAssetKey;


@interface SLPhotoCollectionViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
{
    //所有的图片类
    NSMutableArray *_allAssets;
    //选择的图片类
    NSMutableArray *_selectAssets;
    //图片管理库
    ALAssetsLibrary *_assetsLibrary;
    CGFloat _imageWidth;
    UILabel *_numLabel;
    UIButton *_completeButton;
    UIButton *_previewButton;
    BOOL _fromPreview;
}
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIView *bottomView;
@end

@implementation SLPhotoCollectionViewController

static NSString * const reuseIdentifier_image = @"Cell2";

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_fromPreview) {
        [_collectionView reloadData];
        _fromPreview = NO;
    }
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _numberOfRow = 3;
        _maxImageNumber = 9;
        _mediaType = JLFMediaTypePhoto;
        self.title =  JFBaseLocalizedString(@"相册");

    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.bottomView];

    if (!_urls) {
        _urls = [NSMutableArray arrayWithCapacity:0];
    }
    if (!_thumbImages) {
        _thumbImages = [NSMutableArray arrayWithCapacity:0];
    }
    
    
    _imageWidth = (CGFloat)(CGRectGetWidth([UIScreen mainScreen].bounds) - kSpace * (_numberOfRow - 1)) / _numberOfRow;
    _selectAssets = [NSMutableArray arrayWithCapacity:0];
    [self loadImages];
    [self setNumLabelContent];
}

- (void)cancelSelected {
    [_selectAssets removeAllObjects];
    _bottomView.hidden = YES;
    [self.collectionView reloadData];
}

- (void)loadImages {
    //加载所有图片

    if (_allAssets) {
        [_allAssets removeAllObjects];
    }else{
        _allAssets = [NSMutableArray arrayWithCapacity:0];
    }
    
    _assetsLibrary = [[ALAssetsLibrary alloc] init];
    ALAssetsFilter *assetsFilter =  [ALAssetsFilter allPhotos];
    
    ALAssetsLibraryGroupsEnumerationResultsBlock resultsBlock = ^(ALAssetsGroup *group, BOOL *stop) {
        
        if (group)
        {
            [group setAssetsFilter:assetsFilter];
            
            if (group.numberOfAssets > 0)
            {
                //有图片的相册group
                ALAssetsGroupEnumerationResultsBlock assetsEnumerationBlock =
                
                ^(ALAsset *result, NSUInteger index, BOOL *stop) {
                    
                    if (result) {
                        [_allAssets addObject:result];
                        
                        NSURL *url = [[result  defaultRepresentation] url];
                        if ([_urls containsObject:url]) {
                            [_selectAssets addObject:result];
                        }
                    }
                };
                
                ALAssetsFilter *onlyPhotosFilter;
                switch (_mediaType) {
                    case JLFMediaTypeAll: {
                        onlyPhotosFilter = [ALAssetsFilter allAssets];
                        break;
                    }
                    case JLFMediaTypePhoto: {
                        onlyPhotosFilter = [ALAssetsFilter allPhotos];
                        break;
                    }
                    case JLFMediaTypeVideo: {
                        onlyPhotosFilter = [ALAssetsFilter allVideos];
                        break;
                    }
                }
                
                
                [group setAssetsFilter:onlyPhotosFilter];
                [group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:assetsEnumerationBlock];
            }
        }
        else
        {
            //相册加载完了
            [self.collectionView reloadData];
        }
    };
    
    
    ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {
        
        [self showNoAuthView];
        
    };
    
    [_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
                                      usingBlock:resultsBlock
                                    failureBlock:failureBlock];
    
    NSUInteger type = ALAssetsGroupEvent;
    [_assetsLibrary enumerateGroupsWithTypes:type
                                      usingBlock:resultsBlock
                                    failureBlock:failureBlock];
}

//未授权
- (void)showNoAuthView {
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 100)];
    label.text = JFBaseLocalizedString(@"me.noAlbumAuth");
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor grayColor];
    label.center = CGPointMake(CGRectGetWidth([UIScreen mainScreen].bounds)/2.0, (CGRectGetHeight([UIScreen mainScreen].bounds)-20-44)/2.0);
    label.numberOfLines = 0;
    [self.view addSubview:label];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    [self setNumLabelContent];
    return _allAssets.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier_image forIndexPath:indexPath];
    ALAsset *result = _allAssets[indexPath.row];
    UIImage *img = [[UIImage alloc] initWithCGImage:result.thumbnail];
    
    //图片
    UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:101];
    if (imageView) {
        imageView.image = img;
    }else{
        imageView = [[UIImageView alloc] initWithImage:img];
        imageView.frame = CGRectMake(0, 0, _imageWidth, _imageWidth);
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.tag = 101;
        [cell.contentView addSubview:imageView];
    }
    //按钮
    UIButton *button = (UIButton *)[cell.contentView viewWithTag:103];
    if (!button) {
        button = [UIButton buttonWithType:UIButtonTypeCustom];
        CGFloat width = _imageWidth*0.3;
        button.frame = CGRectMake(_imageWidth-width, 0, width, width);
        button.tag = 103;
        button.backgroundColor = [UIColor clearColor];
        [button setImage:JFBaseBuddleImage(@"select_nomal") forState:UIControlStateNormal];
        [button setImage:JFBaseBuddleImage(@"select_highlight") forState:UIControlStateSelected];
        [button addTarget:self action:@selector(selectButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:button];
    }
    objc_setAssociatedObject(button, &kButtonAssetKey, _allAssets[indexPath.row], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    button.selected = [_selectAssets containsObject:_allAssets[indexPath.row]];
    return cell;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    SLDeleteAndSelectPhotoViewController *deleteCtl = [[SLDeleteAndSelectPhotoViewController alloc] initSelectModelWithAllAssets:_allAssets
                                                                                                                selectAssets:_selectAssets
                                                                                                           currentImageIndex:indexPath.row
                                                                                                              maxImageNumber:_maxImageNumber
                                                                                                                 thumbImages:_thumbImages
                                                                                                                    hdImages:nil
                                                                                                                        urls:_urls
                                                                                                                        delegate:(id<SLDeleteAndEditPhotoViewControllerDelegate>)_delegateCM];
    [self.navigationController pushViewController:deleteCtl animated:YES];
    _fromPreview = YES;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(_imageWidth, _imageWidth);
}

//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(kSpace, 0, kSpace, 0);
}

//最小行距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return kSpace;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return kSpace;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

#pragma mark - buttonClicked

- (void)selectButtonClicked:(UIButton *)sender {
    id asset = objc_getAssociatedObject(sender, &kButtonAssetKey);
    
    if ([_selectAssets containsObject:asset]) {
        [_selectAssets removeObject:asset];
        
        NSURL *url = [[asset  defaultRepresentation] url];
        if ([_urls containsObject:url]) {
            NSInteger index = [_urls indexOfObject:url];
            [_urls removeObjectAtIndex:index];
            [_thumbImages removeObjectAtIndex:index];
        }
        
    }else{
        if (_thumbImages.count < _maxImageNumber) {
            [_selectAssets addObject:asset];
            
            ALAsset *result = asset;
            NSURL *url = [[result  defaultRepresentation] url];
            UIImage *thumbnail = [[UIImage alloc] initWithCGImage:result.thumbnail];

            [_thumbImages addObject:thumbnail];
            [_urls addObject:url];
        }else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:JFBaseLocalizedString(@"您最多只能选择%ld张照片"), _selectAssets.count] message:nil delegate:nil cancelButtonTitle:JFBaseLocalizedString(@"我知道了") otherButtonTitles:nil, nil];
            [alertView show];
        }
    }
    
    [_collectionView reloadData];
}

- (void)completeButtonClicked:(UIButton *)sender{
    if (_selectAssets.count == 0) {
        return;
    }

    //得到高清图片数组images 和缩略图数组thumbnails
    if (self.delegateCM && [self.delegateCM respondsToSelector:@selector(filishSelectThumbImages:urls:)]) {
        [self.delegateCM filishSelectThumbImages:_thumbImages urls:_urls];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)previewButtonClicked:(UIButton *)sender {
    if (_selectAssets.count == 0) {
        return;
    }
    //预览
#warning 删除hdImage
    SLDeleteAndSelectPhotoViewController *deleteCtl = [[SLDeleteAndSelectPhotoViewController alloc] initSelectModelWithAllAssets:_selectAssets
                                                                                                                selectAssets:_selectAssets
                                                                                                           currentImageIndex:0
                                                                                                              maxImageNumber:_maxImageNumber
                                                                                                                 thumbImages:_thumbImages
                                                                                                                    hdImages:nil
                                                                                                                            urls:_urls
                                                                                                                        delegate:(id<SLDeleteAndEditPhotoViewControllerDelegate>)_delegateCM];
    [self.navigationController pushViewController:deleteCtl animated:YES];
    _fromPreview = YES;
}

#pragma mark - Private Methods

- (void)setNumLabelContent {
    _numLabel.hidden = _selectAssets.count == 0;
    _numLabel.text = [NSString stringWithFormat:@"%lu",(unsigned long)_selectAssets.count];
    
    _previewButton.enabled = _selectAssets.count > 0;
    _completeButton.enabled = _selectAssets.count > 0;
}

#pragma mark - Getter

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,
                                                                             0,
                                                                             CGRectGetWidth([UIScreen mainScreen].bounds),
                                                                             CGRectGetHeight([UIScreen mainScreen].bounds) - 64 - kBottomViewHeight)
                                             collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = HexColor(@"#ffffff");
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier_image];
    }
    return _collectionView;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc]init];
        _bottomView.backgroundColor = [UIColor colorWithHexString:@"#f4f5f6"];
        [self.view addSubview:_bottomView];
        _bottomView.frame = CGRectMake(0, CGRectGetMaxY(_collectionView.frame), CGRectGetWidth([UIScreen mainScreen].bounds), kBottomViewHeight);
        
        _previewButton = [[UIButton alloc]init];
        _previewButton.titleLabel.font = [UIFont systemFontOfSize:15];
        _previewButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_previewButton setTitle:JFBaseLocalizedString(@"预览") forState:UIControlStateNormal];
        [_previewButton setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
        [_previewButton setTitleColor:[UIColor colorWithHexString:@"#c2c2c2"] forState:UIControlStateDisabled];

        [_bottomView addSubview:_previewButton];
        [_previewButton sizeToFit];
        _previewButton.frame = CGRectMake(10, 0, CGRectGetWidth(_previewButton.frame), CGRectGetHeight(_bottomView.frame));
        
        _completeButton = [[UIButton alloc]init];
        _completeButton.titleLabel.font = [UIFont systemFontOfSize:15];
        _completeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_completeButton setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
        [_completeButton setTitleColor:[UIColor colorWithHexString:@"#c2c2c2"] forState:UIControlStateDisabled];

        [_completeButton setTitle:JFBaseLocalizedString(@"完成") forState:UIControlStateNormal];
        [_bottomView addSubview:_completeButton];
        [_completeButton sizeToFit];
        _completeButton.frame = CGRectMake(CGRectGetWidth(_bottomView.frame)-CGRectGetWidth(_completeButton.frame)-10, 0, CGRectGetWidth(_completeButton.frame), CGRectGetHeight(_bottomView.frame));
        
        
        _numLabel = [[UILabel alloc]init];
        [_bottomView insertSubview:_numLabel belowSubview:_completeButton];
        _numLabel.font = [UIFont systemFontOfSize:18];
        _numLabel.textAlignment = NSTextAlignmentCenter;
        _numLabel.textColor = HexColor(@"#ffffff");
        _numLabel.backgroundColor = [UIColor colorWithHexString:@"#ff5a23"];
        _numLabel.frame = CGRectMake(CGRectGetMinX(_completeButton.frame)-30, (CGRectGetHeight(_bottomView.frame) - 24) / 2.0, 24, 24);
        _numLabel.layer.cornerRadius = CGRectGetWidth(_numLabel.frame) / 2.0;
        _numLabel.layer.masksToBounds = YES;
        _completeButton.frame = CGRectMake(CGRectGetMinX(_completeButton.frame) - CGRectGetWidth(_numLabel.frame), 0, CGRectGetWidth(_completeButton.frame) + CGRectGetWidth(_numLabel.frame), CGRectGetHeight(_bottomView.frame));

        UILabel *topLine = [[UILabel alloc]init];
        topLine.backgroundColor = [UIColor colorWithHexString:@"#dddddd"];
        [_bottomView addSubview:topLine];
        topLine.frame = CGRectMake(0, 0, CGRectGetWidth(_bottomView.frame), 0.5);
        
        [_previewButton addTarget:self action:@selector(previewButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_completeButton addTarget:self action:@selector(completeButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bottomView;
}

#pragma mark - Class Method

// Helper methods for thumbnailForAsset:maxPixelSize:
static size_t getAssetBytesCallback(void *info, void *buffer, off_t position, size_t count) {
    ALAssetRepresentation *rep = (__bridge id)info;
    
    NSError *error = nil;
    size_t countRead = [rep getBytes:(uint8_t *)buffer fromOffset:position length:count error:&error];
    
    if (countRead == 0 && error) {
        // We have no way of passing this info back to the caller, so we log it, at least.
        NSLog(@"thumbnailForAsset:maxPixelSize: got an error reading an asset: %@", error);
    }
    
    return countRead;
}

static void releaseAssetCallback(void *info) {
    // The info here is an ALAssetRepresentation which we CFRetain in thumbnailForAsset:maxPixelSize:.
    // This release balances that retain.
    CFRelease(info);
}

+ (UIImage *)thumbnailForAsset:(ALAsset *)asset maxPixelSize:(NSUInteger)size {
    NSParameterAssert(asset != nil);
    NSParameterAssert(size > 0);
    
    ALAssetRepresentation *rep = [asset defaultRepresentation];
    
    CGDataProviderDirectCallbacks callbacks = {
        .version = 0,
        .getBytePointer = NULL,
        .releaseBytePointer = NULL,
        .getBytesAtPosition = getAssetBytesCallback,
        .releaseInfo = releaseAssetCallback,
    };
    
    CGDataProviderRef provider = CGDataProviderCreateDirect((void *)CFBridgingRetain(rep), [rep size], &callbacks);
    CGImageSourceRef source = CGImageSourceCreateWithDataProvider(provider, NULL);
    
    CGImageRef imageRef = CGImageSourceCreateThumbnailAtIndex(source, 0, (__bridge CFDictionaryRef) @{
                                                                                                      (NSString *)kCGImageSourceCreateThumbnailFromImageAlways : @YES,
                                                                                                      (NSString *)kCGImageSourceThumbnailMaxPixelSize : [NSNumber numberWithInteger:size],
                                                                                                      (NSString *)kCGImageSourceCreateThumbnailWithTransform : @YES,
                                                                                                      });
    CFRelease(source);
    CFRelease(provider);
    
    if (!imageRef) {
        return nil;
    }
    
    UIImage *toReturn = [UIImage imageWithCGImage:imageRef];
    
    CFRelease(imageRef);
    
    return toReturn;
}
@end
